package cn.fws.meap.user.service.impl;

import java.util.*;

import cn.fws.framework.utils.StringUtils;
import cn.fws.framework.web.contoller.JsonResponse;
import cn.fws.meap.community.enums.ArticleTypeEnum;
import cn.fws.meap.community.service.ICreationService;
import cn.fws.meap.community.vo.CreationDetaileVo;
import cn.fws.meap.system.constants.SortCreateTime;
import cn.fws.meap.user.entity.Account;
import cn.fws.meap.user.enums.UserIsBindEnums;
import cn.fws.meap.user.mapper.ConcernMapper;
import cn.fws.meap.user.service.IAccountService;
import cn.fws.meap.user.vo.ConcernInitMsgVo;
import cn.fws.meap.user.vo.UserDetailsVo;
import cn.fws.meap.user.vo.UserReplyListVo;
import cn.fws.meap.utils.QiNiuUtil;
import cn.fws.meap.utils.logBug.SysLog;
//import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
/*import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;*/
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import cn.fws.framework.utils.ConvertUtils;
import cn.fws.meap.user.mapper.UserMapper;
import cn.fws.meap.user.entity.User;
import cn.fws.meap.user.service.IUserService;
import org.springframework.transaction.annotation.Transactional;


/**
 * 个人用户 服务层实现
 *
 * @author chenkh
 * @date 2019-03-07
 */
@Service
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IAccountService accountService;

    @Autowired
    private ICreationService creationService;
    @Autowired
    private ConcernMapper concernMapper;
//    @Autowired
//    private MongoTemplate mongoTemplate;

    /**
     * 查询个人用户信息
     *
     * @param id 个人用户ID
     * @return 个人用户信息
     */
    @Override
    public User selectById(String id) {
        return userMapper.selectById(id);
    }

    @Override
    public User selectByOpenId(String openid) {
        return userMapper.selectByOpenId(openid);
    }

    /**
     * 查询个人用户列表
     *
     * @param user 个人用户信息
     * @return 个人用户集合
     */
    @Override
    public List<User> selectList(User user) {
        return userMapper.selectList(user);
    }

    /**
     * 新增个人用户
     *
     * @param user 个人用户信息
     * @return 结果
     */
    @Override
    public JsonResponse insert(User user) {
// 从redis中取出生成的uuid 设置主键

        String userId = (String) redisTemplate.opsForValue().get("userId"+user.getId());

        User user1 = selectById(userId);
        if(!userId.equals(user.getId())){
            return JsonResponse.error("注册失败用户id不同");
        }else if(StringUtils.isEmpty(userId)){
            return JsonResponse.error("你要重新获取code");
        }else if (StringUtils.isNotNull(user1) && userId.equals(user1.getId())){
            return JsonResponse.error("你重复注册了",0);
        }else {
            //从redis域中获取openid存入user中
            String openid = (String) redisTemplate.opsForValue().get("openid"+userId);
            user.setId(user.getId());
            user.setOpenid(openid);

            user.setIsBind(UserIsBindEnums.NO_BIND.getCode());
            // 设置创建时间
            user.setCreateTime(new java.util.Date());

            int insert = userMapper.insert(user);





        //添加账户消费记录
        Account account = new Account();
        account.setOpenid(user.getId());
        accountService.insert(account);
        }
        return JsonResponse.success();
    }

    /**
     * 修改个人用户
     *
     * @param user 个人用户信息
     * @return 结果
     */
    @Override
    public int update(User user) {
        // 设置修改时间
        user.setUpdateTime(new java.util.Date());
        return userMapper.update(user);
    }

    /**
     * 删除个人用户对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteByIds(String ids) {
        return userMapper.deleteByIds(ConvertUtils.toStrArray(ids));
    }

    /**
     * 账户绑定
     *
     * @param openId
     * @param isBindEnums
     * @return
     */
    @Override
    public int updateBind(String openId, String isBindEnums) {


        return userMapper.updateBind(openId, isBindEnums);
    }


    @Override
    public UserDetailsVo selectUserInformation(String itOpenId) {
        UserDetailsVo userDetailsVo = userMapper.selectById(itOpenId);
        ConcernInitMsgVo concernInitMsgVo =concernMapper.selectFansCount(itOpenId);
        if(concernInitMsgVo == null){
            userDetailsVo.setConcernCount("0");
            userDetailsVo.setFansCount("0");
        }else {
            userDetailsVo.setConcernCount(concernInitMsgVo.getConcernCount());
            userDetailsVo.setFansCount(concernInitMsgVo.getFansCount());
        }


        return userDetailsVo;
    }


    /**
     * 个人文章问题，回复 回答
     *
     * @param openId
     * @return
     */
    @SysLog
    @Override
    public List<UserReplyListVo> selectUserReplyList(String openId) {
        List<UserReplyListVo> replyList = userMapper.selectUserReplyList(openId);
        List<UserReplyListVo> answerList = userMapper.selectUserAnswerList(openId);
        List list2 = new ArrayList();
        //循环回复添加时间到集合中
        for (UserReplyListVo userReplyListVo : replyList) {
            userReplyListVo.setReplyType(ArticleTypeEnum.REPLY.getCode());
            list2.add(userReplyListVo.getCreatTime());
        }
        //循环问答添加时间到集合中
        for (UserReplyListVo userAnswerListVo : answerList) {
            userAnswerListVo.setAnswerType(ArticleTypeEnum.ANSWER.getCode());
            list2.add(userAnswerListVo.getCreatTime());
        }

        Collections.sort(list2);
        System.out.println("一共的时间------" + list2);
        //排序
        List<UserReplyListVo> sortList = replySort(replyList, answerList, list2);


        return sortList;
    }

    /**
     * selectUserReplyList排序引用
     *
     * @param replyList
     * @param answerList
     * @param list2
     * @return
     */
    public List replySort(List<UserReplyListVo> replyList, List<UserReplyListVo> answerList, List list2) {
        List<UserReplyListVo> newList = new LinkedList<>();
        //判断传来的集合是否为0
        if (replyList.size() != 0 && answerList.size() != 0) {
            for (int i = 0; i < list2.size(); i++) {
                System.out.println(list2.get(i));
                for (UserReplyListVo userReplyListVo : replyList) {
                    if (list2.get(i).equals(userReplyListVo.getCreatTime())) {
                        if (!newList.contains(userReplyListVo)) {
                            userReplyListVo.setReplyMsg(QiNiuUtil.getFileMsg(userReplyListVo.getReplyMsg()));
                            userReplyListVo.setArticleMsg(QiNiuUtil.getFileMsg(userReplyListVo.getArticleMsg()));
                            ((LinkedList<UserReplyListVo>) newList).addFirst(userReplyListVo);
                        }
                    }
                    for (UserReplyListVo userAnswerListVo : answerList) {
                        if (list2.get(i).equals(userAnswerListVo.getCreatTime())) {
                            if (!newList.contains(userAnswerListVo)) {

                                userAnswerListVo.setProblemMsg(QiNiuUtil.getFileMsg(userAnswerListVo.getProblemMsg()));

                                userAnswerListVo.setAnswerMsg(QiNiuUtil.getFileMsg(userAnswerListVo.getAnswerMsg()));
                                ((LinkedList<UserReplyListVo>) newList).addFirst(userAnswerListVo);
                            }
                        }

                    }
                }
            }
        } else if (replyList.size() == 0 && answerList.size() != 0) {

            newList = replyFor(answerList, list2);
            System.out.println("回答" + newList);
        } else if (replyList.size() != 0 && answerList.size() == 0) {

            newList = replyFor(replyList, list2);
            System.out.println("回复" + newList);
        }
        System.out.println("排序对象------" + newList);
        return newList;
    }

    /**
     * replySort循环引用
     *
     * @param replyList
     * @param list2
     * @return
     */
    public List<UserReplyListVo> replyFor(List<UserReplyListVo> replyList, List list2) {
        List<UserReplyListVo> newList = new LinkedList<>();
        for (int i = 0; i < list2.size(); i++) {
            for (UserReplyListVo userReplyListVo : replyList) {
                if (list2.get(i).equals(userReplyListVo.getCreatTime())) {
                    if (!newList.contains(userReplyListVo)) {
                        if (StringUtils.isNotEmpty(userReplyListVo.getProblemMsg()) || StringUtils.isNotEmpty(userReplyListVo.getAnswerMsg())) {
                            userReplyListVo.setProblemMsg(QiNiuUtil.getFileMsg(userReplyListVo.getProblemMsg()));

                            userReplyListVo.setAnswerMsg(QiNiuUtil.getFileMsg(userReplyListVo.getAnswerMsg()));
                        } else {
                            userReplyListVo.setReplyMsg(QiNiuUtil.getFileMsg(userReplyListVo.getReplyMsg()));
                            userReplyListVo.setArticleMsg(QiNiuUtil.getFileMsg(userReplyListVo.getArticleMsg()));
                        }

                        ((LinkedList<UserReplyListVo>) newList).addFirst(userReplyListVo);
                    }
                }
            }
        }
        return newList;
    }

    /**
     * 个人查询创作记录和回复
     *
     * @param openId
     * @return
     */
    @SysLog
    @Override
    public List selectPostReplyList(String openId) {
        List<UserReplyListVo> replyList = selectUserReplyList(openId);
        List<CreationDetaileVo> creationList = creationService.selectListUser(openId, SortCreateTime.createTimeDesc);
        List list = new ArrayList();
        List linkedList = new LinkedList();
        for (UserReplyListVo userReplyListVo : replyList) {
            list.add(userReplyListVo.getCreatTime());
        }
        for (CreationDetaileVo creationDetaileVo : creationList) {
            list.add(creationDetaileVo.getCreateTime());
        }

        Collections.sort(list);

        //List sortList = replySort(replyList, answerList, list);
        //判断传来的集合是否为0
        if (replyList.size() != 0 && creationList.size() != 0) {
            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i));
                for (UserReplyListVo userReplyListVo : replyList) {
                    if (list.get(i).equals(userReplyListVo.getCreatTime())) {
                        if (!linkedList.contains(userReplyListVo)) {
                            ((LinkedList) linkedList).addFirst(userReplyListVo);
                        }
                    }
                    for (CreationDetaileVo creationListVo : creationList) {
                        if (list.get(i).equals(creationListVo.getCreateTime())) {
                            if (!linkedList.contains(creationListVo)) {
                                ((LinkedList) linkedList).addFirst(creationListVo);
                            }
                        }

                    }
                }
            }
        } else if (replyList.size() == 0 && creationList.size() != 0) {
            for (int i = 0; i < list.size(); i++) {
                for (CreationDetaileVo creationDetaileVo : creationList) {
                    System.out.println("没有回复和回答");
                    if (list.get(i).equals(creationDetaileVo.getCreateTime())) {
                        if (!linkedList.contains(creationDetaileVo)) {
                            ((LinkedList) linkedList).addFirst(creationDetaileVo);
                        }
                    }
                }
            }
        } else if (replyList.size() != 0 && creationList.size() == 0) {
            for (int i = 0; i < list.size(); i++) {
                System.out.println("没有发布问题和文章");
                for (UserReplyListVo userReplyListVo : replyList) {
                    if (list.get(i).equals(userReplyListVo.getCreatTime())) {
                        if (!linkedList.contains(userReplyListVo)) {
                            ((LinkedList) linkedList).addFirst(userReplyListVo);
                        }
                    }
                }
            }
        }


        return linkedList;
    }


    /*public void saveUser(User user){
        System.out.println("保存数据"+user);
        mongoTemplate.save(user);
        System.out.println("保存成功");
    }


    @Override
    public void deleteUser(String nickname) {
        System.out.println("删除数据"+nickname);
        Query query=new Query(Criteria.where("nickname").is(nickname));
        System.out.println(mongoTemplate.remove(query,User.class));

    }

    @Override
    public long updateUser(User user) {
        System.out.println("更新数据"+user);
        Query query=new Query(Criteria.where("nickname").is(user.getNickname()));
        Update update= new Update().set("sex", user.getSex()).set("city", user.getCity());
        //更新查询返回结果集的第一条
        UpdateResult result =mongoTemplate.updateFirst(query,update,User.class);
        //更新查询返回结果集的所有
        // mongoTemplate.updateMulti(query,update,UserEntity.class);
        System.out.println("保存成功");
        if(result!=null) {

            return result.getMatchedCount();
        } else {
            return 0;
        }

    }

    @Override
    public User getUser(String nickName) {
        System.out.println("查询数据"+nickName);
        Query query=new Query(Criteria.where("nickname").is(nickName));
        User user = mongoTemplate.findOne(query , User.class);
        System.out.println(user);
        return user;

    }*/


}
